#!/usr/bin/env python3
#created by anchengan in 20250315
import paks.http.server as httpserver
import paks.urllib.parse as urllibparse
from utils.ID_tools import create_id
# DATA_SAVE={"Acautoai-Proj":[["ID","NAME","COMMAND","STATE"]],"ProjWatch":{"ID":"TIMESTAMP"}}
DATA_SAVE={"Acautoai-Proj":[],"ProjWatch":{}}

class SimpleHTTPRequestHandler(httpserver.BaseHTTPRequestHandler):

    def do_GET(self):
        global DATA_SAVE
        parsed_url = urllibparse.urlparse(self.path)
        # query_params = urllibparse.parse_qs(parsed_url.query)

        #print("Received GET request with params:", query_params)

        filename = './utils/boardmain.html'
 
        with open(filename, 'r', encoding='utf-8') as file:
            response_content = file.read()
        data_insert="<tr>\n"
        for data_insert_group in DATA_SAVE["Acautoai-Proj"]:
            for data_insert_item in data_insert_group:
                data_insert=data_insert+f"<td>{data_insert_item}</td>\n"
            data_insert=data_insert+"</tbody>\n<tbody>\n"
        response_content=response_content.replace("[Acautoai]",data_insert)
        response_content=response_content.encode('utf-8')


        self.send_response(200)

        self.send_header("Content-type", "text/html")

        self.end_headers()

        self.wfile.write(response_content)

    

    def do_POST(self):
        global DATA_SAVE
        content_length = int(self.headers['Content-Length'])

        post_data = self.rfile.read(content_length)

        parsed_data = urllibparse.parse_qs(post_data.decode('utf-8'))
        #parsed_data format: Func:xx,para1:xx,para2:xx
        response_content = "Unknown command".encode('utf-8')

        # print("Received POST data:", parsed_data)
        #add a new proj
        if parsed_data["Func"][0]=="add_proj":
            for data_insert_group in DATA_SAVE["Acautoai-Proj"]:
                if data_insert_group[0]==parsed_data["para1"][0]:
                    response_content = "add proj failed,SAME ID!!!".encode('utf-8')
                    break
                
            else:
                DATA_SAVE["Acautoai-Proj"].append([parsed_data["para1"][0],parsed_data["para2"][0],parsed_data["para3"][0],parsed_data["para4"][0]])
                DATA_SAVE["ProjWatch"][parsed_data["para1"][0]]=create_id()
                response_content = "add proj success".encode('utf-8')

        #show all proj
        if parsed_data["Func"][0]=="show_proj":
            response_content="|ID|NAME|COMMAND|STATE|\n"
            for data_insert_group in DATA_SAVE["Acautoai-Proj"]:
                for data_insert_item in data_insert_group:
                    response_content=response_content+f"{data_insert_item} "
                response_content+="\n"
            response_content=response_content.encode('utf-8')
        #get command
        if parsed_data["Func"][0]=="get_command":
            for data_insert_group in DATA_SAVE["Acautoai-Proj"]:
                if data_insert_group[0]==parsed_data["para1"][0]:
                    response_content=data_insert_group[2].encode('utf-8')
                    break
        #set command
        if parsed_data["Func"][0]=="set_command":
            for ind,data_insert_group in enumerate(DATA_SAVE["Acautoai-Proj"]):
                if data_insert_group[0]==parsed_data["para1"][0]:
                    DATA_SAVE["Acautoai-Proj"][ind][2]=parsed_data["para3"][0]
                    response_content = "set_command success".encode('utf-8')
                    break
            else:
                response_content = "set_command fail".encode('utf-8')
        #refresh proj by ID
        if parsed_data["Func"][0]=="refresh_proj":
            for ind,data_insert_group in enumerate(DATA_SAVE["Acautoai-Proj"]):
                if data_insert_group[0]==parsed_data["para1"][0]:
                    DATA_SAVE["Acautoai-Proj"][ind]=[parsed_data["para1"][0],parsed_data["para2"][0],parsed_data["para3"][0],parsed_data["para4"][0]]
                    response_content = "refresh proj success".encode('utf-8')
                    break
            else:
                response_content = "no proj refreshed".encode('utf-8')


        #watchdog
        if parsed_data["Func"][0]=="watchdog":
            if parsed_data["para1"][0]=="0":
                #master watchdog
                for watchID ,watchTS in DATA_SAVE["ProjWatch"].items():
                    if float(create_id())-float(watchTS)>10:
                        for ind,data_insert_group in enumerate(DATA_SAVE["Acautoai-Proj"]):
                            if data_insert_group[0]==watchID:
                                DATA_SAVE["Acautoai-Proj"][ind][3]="END"
                                break
                response_content = "master watchdog work success".encode('utf-8')

            else:
                #watch refresh
                DATA_SAVE["ProjWatch"][parsed_data["para1"][0]]=create_id()
                response_content = "watchdog work success".encode('utf-8')
        print(DATA_SAVE)

        

        # 发送响应状态码

        self.send_response(200)

        

        # 发送响应头

        self.send_header("Content-type", "text/html")

        self.end_headers()

        

        # 发送响应内容

        self.wfile.write(response_content)

 

def run_server(host="0.0.0.0",port=65532,server_class=httpserver.HTTPServer, handler_class=SimpleHTTPRequestHandler):

    server_address = (host, port)

    httpd = server_class(server_address, handler_class)

    print(f"Starting acaboard server on host: {host} port: {port}")

    httpd.serve_forever()

 
